package com.zj.learn.ssq;

import com.alibaba.fastjson.JSON;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Jsoup实践
 * Created by Yangxi on 2017/5/9 0009.
 */
public class NetGetSSQRecord {
    private static final String fileName = "ssq.txt";
    private static final String baseUrl = "http://kaijiang.zhcw.com/zhcw/html/ssq/list.html";
    private static final String newBaseUrlPrefix = "http://kaijiang.zhcw.com/zhcw/inc/ssq/ssq_wqhg.jsp?pageNum=";
    private static Set<Integer> ids = new HashSet<>();
    private static List<Ssq> ssqs = new ArrayList<>();
    public static void main(String[] args) {
//        sycSsqRecord();
        while (true) {
            Ssq ssq = randomSsq();
            if (ssq.getBlue().equals(9)) {
                System.out.println(JSON.toJSONString(ssq));
                break;
            }
        }
    }

    private static Ssq randomSsq() {
        List<Integer> allRed = new ArrayList<>();
        for (int i = 0; i < 33; i++) {
            allRed.add(i + 1);
        }
        Ssq ssq = new Ssq();
        Random random = new Random();
        List<Integer> red = new ArrayList<>();
        for (int i = 0; i < 6; i++) {
            int index = random.nextInt(allRed.size());
            red.add(allRed.remove(index));
        }
        ssq.setReds(red.stream().sorted().map(s -> "" + s).collect(Collectors.joining(",")));
        ssq.setBlue(random.nextInt(16) + 1);
        return ssq;
    }

    private static void sycSsqRecord() {
        try {
            readSsqFile();

            updateSsqDataFromNetwork();

            write2File();

            System.out.println("========统计一波=========");
            int i = 0;
            for (int j = 1; j <= 16; j++) {
                for (Ssq ssq : ssqs) {
                    if (ssq.getBlue().equals(j)) {
                        System.out.println(j + "================" + i);
                        i = 0;
                        break;
                    } else {
                        i++;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void updateSsqDataFromNetwork() throws Exception {
        Document document = Jsoup.connect(baseUrl).get();
        Elements elements = document.select(".pg");
        int page = Integer.parseInt(elements.get(0).child(0).ownText());
        System.out.println("总页数：" + page);
        for (int i = 1; i <= page; i++) {
            try {
                Thread.sleep(1000L);
            } catch (Exception e) {
                e.printStackTrace();
            }
            Document doc = Jsoup.connect(newBaseUrlPrefix+i).get();
            List<Ssq> onePageDataList = onePageDataList(doc);
            for (Ssq ssq : onePageDataList) {
                if (ids.contains(ssq.getOpenNum())) {
                    System.out.println("已经获取过了，停止！！！");
                    return;
                }
                ssqs.add(ssq);
                ids.add(ssq.getOpenNum());
            }

            System.out.println("=====" + i);
        }
    }

    private static void write2File() throws IOException {
        List<String> lines = new ArrayList<>();
        ssqs.sort(Comparator.comparing(Ssq::getOpenTime));
        Collections.reverse(ssqs);
        for (Ssq ssq : ssqs) {
            lines.add(JSON.toJSONString(ssq));
        }
        Files.write(Paths.get(fileName), lines);
    }

    private static void readSsqFile() throws IOException {
        Path path = Paths.get(fileName);
        if (!Files.exists(path)) {
            Files.createFile(path);
        }
        List<String> lines = Files.readAllLines(Paths.get(fileName));
        for (String line : lines) {
            Ssq ssq = JSON.parseObject(line, Ssq.class);
            ssqs.add(ssq);
            ids.add(ssq.getOpenNum());
        }
    }

    /**
     * 获取一页数据
     *
     * @param document
     * @throws ParseException
     */
    private static List<Ssq> onePageDataList(Document document) throws ParseException {
        List<Ssq> list = new ArrayList<>();
        Elements trs = document.getElementsByTag("tr");
        for (int i = 0; i < trs.size(); i++) {
            Element element = trs.get(i);
            int childSize = element.childNodeSize();
            if (childSize != 15) {
                continue;
            }
            Ssq ssq = getSsq(element);
            System.out.println(JSON.toJSONString(ssq));
            list.add(ssq);
        }
        return list;
    }

    private static Ssq getSsq(Element element) throws ParseException {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date openTime = format.parse(element.child(0).ownText());
        int openNum = Integer.parseInt(element.child(1).ownText());
        Element balls = element.child(2);
        String op = ",";
        String reds = balls.child(0).ownText()+op+
                balls.child(1).ownText()+op+
                balls.child(2).ownText()+op+
                balls.child(3).ownText()+op+
                balls.child(4).ownText()+op+
                balls.child(5).ownText();
        int blue = Integer.parseInt(balls.child(6).ownText());
        long sales = Long.parseLong(element.child(3).child(0).ownText().replace(op,""));
        int firstPrizeNum = Integer.parseInt(element.child(4).child(0).ownText());
        int secondPrizeNum = Integer.parseInt(element.child(5).child(0).ownText());
        return new Ssq(openTime,openNum,reds,blue,sales,firstPrizeNum,secondPrizeNum);
    }
}

class Ssq{
    private Date openTime;
    private Integer openNum;
    private String reds;
    private Integer blue;
    private Long sales;
    private Integer firstPrizeNum;
    private Integer secondPrizeNum;

    public Ssq() {
    }

    public Ssq(Date openTime, Integer openNum, String reds, Integer blue, Long sales, Integer firstPrizeNum, Integer secondPrizeNum) {
        this.openTime = openTime;
        this.openNum = openNum;
        this.reds = reds;
        this.blue = blue;
        this.sales = sales;
        this.firstPrizeNum = firstPrizeNum;
        this.secondPrizeNum = secondPrizeNum;
    }

    public Date getOpenTime() {

        return openTime;
    }

    public void setOpenTime(Date openTime) {
        this.openTime = openTime;
    }

    public Integer getOpenNum() {
        return openNum;
    }

    public void setOpenNum(Integer openNum) {
        this.openNum = openNum;
    }

    public String getReds() {
        return reds;
    }

    public void setReds(String reds) {
        this.reds = reds;
    }

    public Integer getBlue() {
        return blue;
    }

    public void setBlue(Integer blue) {
        this.blue = blue;
    }

    public Long getSales() {
        return sales;
    }

    public void setSales(Long sales) {
        this.sales = sales;
    }

    public Integer getFirstPrizeNum() {
        return firstPrizeNum;
    }

    public void setFirstPrizeNum(Integer firstPrizeNum) {
        this.firstPrizeNum = firstPrizeNum;
    }

    public Integer getSecondPrizeNum() {
        return secondPrizeNum;
    }

    public void setSecondPrizeNum(Integer secondPrizeNum) {
        this.secondPrizeNum = secondPrizeNum;
    }
}
